<template>
  <div class="Roast">
    <!-- logo -->
    <el-row>
      <el-col class="logicon">Tu👄AO</el-col>
    </el-row>
    <!-- 内容卡片 -->
    <el-card v-loading="loading" element-loading-text="拼命加载中">
      <el-row>
        <el-col class="logiconDesc">吐槽達人</el-col>
        <!-- 排行榜单 -->
        <el-col>
          <el-card>匿名吐槽</el-card>
        </el-col>
        <!-- 吐槽内容 -->
        <el-col>
          <el-tree
            :data="roastData"
            :show-checkbox="false"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <el-col :span="20" style="text-align: left;">{{ node.label }}</el-col>
              <el-col :span="3">{{data.createdAt}}</el-col>
              <el-col :span="1">
                <el-button type="text" size="mini" @click="() => showReplyRoastView(data)">回复</el-button>
              </el-col>
              <!-- <el-button type="text" size="mini" @click="() => remove(node, data)">Delete</el-button> -->
            </span>
          </el-tree>
        </el-col>

        <!-- 吐槽模块 -->
        <el-col class="publishedRoast">
          <el-card>
            <el-row>
              <el-col :span="3">
                <el-input :rows="2" placeholder="昵称" v-model="sendRoastNicknaem"></el-input>
              </el-col>
              <el-col :span="20">
                <el-input :rows="2" placeholder="我要吐槽" v-model="sendRoastData">
                  <el-button slot="append" icon="el-icon-success" v-on:click="publishedRoast">吐槽</el-button>
                </el-input>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import AV from "leancloud-storage";
import common from "../common/common.js";

export default {
  data() {
    return {
      loading: false,
      sendRoastData: "",
      sendRoastNicknaem: "",
      roastIDList: [],
      roastData: []
    };
  },
  created() {
    this.queryRoastIDList();
  },
  methods: {
    // 判断 吐槽内容是否为空
    getcurrentValue() {
      return this.sendRoastData.length < 1 || this.sendRoastNicknaem.length < 1;
    },
    // 查询 全部吐槽内容
    queryRoastIDList() {
      this.loading = true;
      //重置 数据源
      this.roastData = [];
      this.roastIDList = [];
      //   开始请求数据
      var query = new AV.Query("RoastRecordList");
      var self = this;
      query.find().then(
        function(results) {
          console.log("查询 success");
          console.log(results);
          for (var i = 0; i < results.length; i++) {
            self.queryRoastData(results[i].id);
          }
        },
        function(error) {
          console.log("查询失败");
          console.log(error);
        }
      );
    },
    // 查询单条吐槽记录
    queryRoastData: function(roastId) {
      var query = new AV.Query("RoastRecordList");
      var self = this;
      query.get(roastId).then(
        function(todo) {
          console.log("查询 成功");
          console.log(todo.attributes.roast);
          if (todo.attributes.roast) {
            self.roastIDList.push(roastId);
            var time = common.myFunction(todo.createdAt);
            todo.attributes.roast["createdAt"] = time;
            self.roastData.push(todo.attributes.roast);
          }
          self.loading = false;
        },
        function(error) {
          console.log("查询 失败");
          console.log(error);
        }
      ).then(function(){
          self.roastData.sort(common.comparedate)
      });
    },
    // 展示回复框
    showReplyRoastView(data) {
      var that = this;
      that
        .$prompt("请输入回复内容", "回复", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputValue: "输入格式： 昵称: 内容"
          //   inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
          //   inputErrorMessage: '邮箱格式不正确'
        })
        .then(({ value }) => {
          if (value.indexOf(":") != -1 || value.indexOf("：") != -1) {
            that.replyRoast(data, value);
          } else {
            that.$alert("请输入昵称并包含冒号 : ", "提示", {
              confirmButtonText: "确定"
            });
          }
        })
        .catch(() => {
          that.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    //  回复吐槽内容
    replyRoast(data, value) {
      this.loading = true;
      var index = data.id;
      var objectId = this.roastIDList[index];
      // 获取数据源中 data
      var temp = this.roastData[index];

      var that = this;
      var Roast = AV.Object.createWithoutData("RoastRecordList", objectId);

      // 添加数据 先创建子类对象
      const newChild = {
        id: index,
        label: value,
        children: []
      };
      //   防止父类没有子类集合
      if (!temp.children) {
        that.$set(temp, "children", []);
      }
      //   添加子类对象
      temp.children.push(newChild);
      console.log(temp);
      Roast.save({ roast: temp }).then(
        function(object) {
          console.log("更新 成功");
          console.log(object);
          data.children.push(newChild);
          that.roastData[index] = temp;
          that.loading = false;
          that.$message({
            type: "success",
            message: "回复成功"
          });
        },
        function(error) {
          // 失败
          console.log(error);
          console.log("更新 失败");
        }
      );
    },
    // 发表吐槽
    publishedRoast(data) {
      if (this.getcurrentValue()) {
        return alert("昵称、内容不能为空");
      }
      this.loading = true;
      var that = this;
      var RoastObject = AV.Object.extend("RoastRecordList");
      var Roast = new RoastObject();
      // 吐槽
      var content = {
        words: "来自" + that.roastNicknaem + "的吐槽",
        roast: {
          id: that.roastIDList.length,
          label: that.sendRoastNicknaem + ": " + that.sendRoastData,
          children: []
        }
      };

      Roast.save(content).then(
        function(object) {
          console.log("插入数据成功");
          // 添加数据 先创建子类对象
          const newChild = {
            id: that.roastIDList.length,
            label: that.sendRoastNicknaem + ": " + that.sendRoastData,
            children: []
          };
          //   防止父类没有子类集合
          if (!data.children) {
            that.$set(data, "children", []);
          }
          //   添加子类对象
          data.children.push(newChild);
          that.queryRoastIDList();
        },
        function(error) {
          // 失败
          console.log(error);
          console.log("插入 失败");
        }
      );
    },
    // 删除
    remove(node, data) {
      //   const parent = node.parent;
      //   const children = parent.data.children || parent.data;
      //   const index = children.findIndex(d => d.id === data.id);
      //   children.splice(index, 1);
      console.log(node);
      console.log(data);
    },

    // 删除数据
    deleteItem: function() {
      if (this.getcurrentValue()) {
        return alert("ID:key:value 不能为空");
      }
      var todo = AV.Object.createWithoutData("TestObject", this.TestObjectId);
      todo.destroy().then(
        function(success) {
          console.log(success);
          console.log("删除 成功");
          this.TestObjectId = "";
        },
        function(error) {
          console.log(error);
          console.log("删除 失败");
        }
      );
    }
  }
};
</script>

<style>
.Roast {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.logicon {
  font-size: 6em;
  color: yellow;
  font-family: "Pacifico", cursive;
}

.logiconDesc {
  font-family: "Pacifico", cursive;
  color: white;
  font-size: 2em;
}

/* eltree */
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
/* 发表吐槽 */
.publishedRoast {
  margin-top: 12px;
}
</style>
